package com.travel.server.manager.impl.command.project.data;

import com.travel.common.excel.ExcelData;
import com.travel.common.exception.WorkCode;
import com.travel.common.exception.WorkException;
import com.travel.common.util.CollectionUtil;
import com.travel.common.util.DateUtil;
import com.travel.common.util.ExcelUtil;
import com.travel.server.manager.dto.request.project.data.ExportProjectProfitListRequest;
import com.travel.server.manager.dto.response.EmptyResponse;
import com.travel.server.manager.dto.response.project.data.QueryProjectProfitListResponse.ProjectProfitItem;
import com.travel.server.manager.impl.command.AbstractCommand;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Author: LiZhenhui
 * @Date: 2018/11/29 12:11
 * @Desc:
 */
@Component
@Slf4j
public class ExportProjectProfitListCommand extends AbstractCommand<ExportProjectProfitListRequest, EmptyResponse> {

    @Autowired
    private QueryProjectProfitListCommand queryProjectProfitListCommand;

    @Override
    protected void checkInput(ExportProjectProfitListRequest request) {
        checkTimeInput(request);
    }

    @Override
    public EmptyResponse handle(ExportProjectProfitListRequest request) {
        Date startTime = DateUtil.getDataTime(request.getStartTime());
        Date endTime = DateUtil.getDataEndTime(request.getEndTime());
        List<ProjectProfitItem> list = queryProjectProfitListCommand.queryProjectProfitItem(startTime, endTime, null, null);
        if(CollectionUtil.isEmpty(list)){
            throw new WorkException(WorkCode.EXCEL_DATA_NULL);
        }

        List<String> title = Arrays.asList("项目", "出行时间", "当期成本", "已售订单", "退款订单", "利润额");
        List<List<Object>> rows = new ArrayList<>();
        for(ProjectProfitItem item : list){
            List<Object> objects = new ArrayList<>();
            objects.add(item.getProject());
            objects.add(DateUtil.YYYY_MM_DD.format(item.getTravelDate()));
            objects.add(item.getCost());
            objects.add(item.getOrder());
            objects.add(item.getRefund());
            objects.add(item.getProject());
            rows.add(objects);
        }
        ExcelData excelData = new ExcelData();
        excelData.setName("利润额");
        excelData.setTitles(title);
        excelData.setRows(rows);
        ExcelUtil.exportExcel(getHttpServletResponse(), "利润额", excelData);

        return new EmptyResponse();
    }
}
